import mongoose from '../config/dbHelper';
import moment from 'moment';

const Schema = mongoose.Schema;
const UserSchema = new Schema({
  username: { type: String, index: { unique: true }, sparse: true },
  password: { type: String },
  email: { type: String },
  createTime: { type: Date },
  updateTime: { type: Date },
  location: { type: String, default: '' },
  gender: { type: String, default: '' },
  mobile: { type: String, match: /^1[3-9](\d{9})$/, default: '' },
  pic: { type: String, default: '/img/header.jpg' },
  regmark: { type: String, default: '' },
  favs: { type: Number, default: 100 },
  roles: { type: Array, default: ['user'] },
  isVip: { type: String, default: '0' },
  count: { type: Number, default: 0 },
  status: { type: Number, default: '0' }
});

UserSchema.statics = {
  getUserInfo: function (username) {
    return this.find({ username }, {
      email: 0,
      password: 0,
      roles: 0
    });
  },
  getUserInfoById: function (uid) {
    return this.find({ _id: uid }, {
      email: 0,
      password: 0,
      roles: 0
    });
  }
};

UserSchema.pre('save', function (next) {
  this.createTime = moment().format('YYYY-MM-DD HH:mm:ss');
  next();
});

UserSchema.pre('update', function (next) {
  this.updateTime = moment().format('YYYY-MM-DD HH:mm:ss');
  next();
});

UserSchema.post('save', function (error, doc, next) {
  if (error.name === 'MongoError' && error.code === 11000) {
    next(new Error('Error: Monngoose has a duplicate key.'));
  } else {
    next(error);
  }
});

// 连接connections，model + Schema
const UserModel = mongoose.model('users', UserSchema);
export default UserModel;
